import json
from dataconfig.file_config import FilePath
from logs.user_log import UserLog

class OperetionJson:

	def __init__(self, file_path=None):
		self.path = FilePath()
		self.log = UserLog().get_log()

	def read_data(self,file_path):
		with open(file_path,encoding='utf-8') as fp:
			try:
				data = json.load(fp)
			except:
				print("json文件为空，或者其他异常！")
			else:
				return data

	# 根据关键字获取数据
	def get_data(self,file_path,key=None):
		data = self.read_data(file_path)
		# self.log.debug('根据关键字获取headers，data')
		if key !=None:
			try:
				return data[key]
			except:
				self.log.error('data: %s没有key"%s"' %(data,key))
		else:
			return data


	# 写json,str格式
	def write_data(self,file_path,data):
		with open(file_path, 'w',encoding='utf-8') as fp:
			fp.write(json.dumps(data))
			self.log.debug('写入数据完毕')

# if __name__ == '__main__':
	# opjson = OperetionJson('F:/A_RuanJian/Py_project/imooc/dataconfig/user.json')
	# print opjson.get_data('use')
